package com.far.game.xiuzhen.common.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.far.game.xiuzhen.common.dto.Visitor;
import com.far.game.xiuzhen.common.exception.BizException;


import java.util.HashMap;
import java.util.Map;

public class JWTUtils {

    /**
     * @param token
     * @param key
     * @description: 验证是否过期
     * @return: boolean
     * @author mike/Fang.J/Q184377367
     * @date: 2022/3/13 18:49
     */
    public static boolean verifyTime(String token, String key) {
        // String key = "aabb";
        // String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzV29yZCI6IjY2Njg4OSIsIm5iZiI6MTYzNTE1MDI3NiwiZXhwIjoxNjM1MTUwODc2LCJ1c2VyTmFtZSI6InpoYW5nc2FuIiwiaWF0IjoxNjM1MTUwMjc2fQ.Cq2AHyrZ-Q7U7O5BBPdEIBrm7aDtjQh4ZDvtIcLzQvg";
        JWT jwt = JWTUtil.parseToken(token);
        boolean verifyKey = jwt.setKey(key.getBytes()).verify();

        boolean verifyTime = jwt.validate(0);
        return verifyTime;
    }


    public static <T> T get(String token, String key,String idx) {
        // String key = "aabb";
        // String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzV29yZCI6IjY2Njg4OSIsIm5iZiI6MTYzNTE1MDI3NiwiZXhwIjoxNjM1MTUwODc2LCJ1c2VyTmFtZSI6InpoYW5nc2FuIiwiaWF0IjoxNjM1MTUwMjc2fQ.Cq2AHyrZ-Q7U7O5BBPdEIBrm7aDtjQh4ZDvtIcLzQvg";
        JWT jwt = JWTUtil.parseToken(token);
        boolean verifyKey = jwt.setKey(key.getBytes()).verify();

        if (verifyKey) {
            return (T) jwt.getPayload(idx);
        } else {
            return null;
        }

    }



    public static String getJwtKey(Visitor visitor){
        Map<String, Object> map = new HashMap<String, Object>() {
            private static final long serialVersionUID = 1L;
            {
                put("userName", visitor.getUserName());
                put("passwd", visitor.getPasswd());
                put("userTid", visitor.getTid());
                //半个月后token失效
                put("expireTime", System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15);
            }
        };
        if(ObjectUtil.isEmpty(AppUtil.JWTKEY)){
            throw new BizException("jwt key must be set");
        }
        return JWTUtil.createToken(map, AppUtil.JWTKEY.getBytes());

    }



}
